﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace BestPrice.Common
{
    internal class Util
    {
        public static void SetPropertyValue(Object source, String ptyName, Object value)
        {
            PropertyInfo pi = source.GetType().GetProperty(ptyName);
            if (pi != null)
                pi.SetValue(source, value, null);
        }

        public static KeyValuePair<String, Object>[] KeyValuePairs(Object obj)
        {
            Type type = obj.GetType();
            var pis = type.GetProperties();
            var list = new List<KeyValuePair<String, Object>>(pis.Length - 2);

            foreach (var pi in pis)
            {
                var field = type.GetField("_" + pi.Name, BindingFlags.Instance | BindingFlags.NonPublic);
                if (field == null || Attribute.IsDefined(field, typeof(NonSerializedAttribute)))
                    continue;

                list.Add(new KeyValuePair<String, Object>(pi.Name, pi.GetValue(obj, null)));
            }

            return list.ToArray();
        }
    }
}
